package net.orange.console;

import java.io.FileOutputStream;
import java.util.Iterator;

import net.orange.console.model.dataset.ConsoleData;
import net.orange.console.model.dataset.ConsoleDataSet;
import net.orange.console.model.dataset.ConsoleMetaData;
import net.orange.console.model.dataset.ConsoleRow;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
 * The excel console writer which implement the ConsoleWriter interface, it can
 * export the console object(like data set) to excel file.
 * 
 */
public class ConsoleExcelWriter implements ConsoleWriter {

	private static int MAX_EXCEL_ROW_COUNT = 65535;

	/*
	 * (non-Javadoc)
	 * 
	 * @see net.orange.console.ConsoleWriter#write(java.lang.String,
	 *      net.orange.console.model.dataset.ConsoleDataSet)
	 */
	public long write(String url, ConsoleDataSet dataSet) throws Exception {

		if (url != null && url.length() > 0 && dataSet != null) {
			// 1.Create the excel work sheet
			HSSFWorkbook workbook = new HSSFWorkbook();
			HSSFSheet sheet = workbook.createSheet("result");

			// 2.Export the title
			Iterator metaDataSet = dataSet.getMetaDataSetIterator();
			short columnIndex = 0;

			while (metaDataSet.hasNext()) {
				ConsoleMetaData metaData = (ConsoleMetaData) metaDataSet.next();

				HSSFRow row = sheet.createRow(0);
				HSSFCell cell = row.createCell(columnIndex);
				cell.setCellValue(metaData.getColumnName());

				columnIndex++;
			}

			// 3.Export the data
			if (dataSet.getRows() != null && dataSet.getRows().size() > 0) {
				short rowIndex = 1;

				for (ConsoleRow dataRow : dataSet.getRows()) {
					columnIndex = 0;

					if (rowIndex > MAX_EXCEL_ROW_COUNT)
						break;

					HSSFRow row = sheet.createRow(rowIndex);

					for (ConsoleData data : dataRow.getDatas()) {
						HSSFCell cell = row.createCell(columnIndex);
						cell.setCellValue(data.getStringValue());

						columnIndex++;
					}
					rowIndex++;
				}
			}

			// 4.Save the file
			FileOutputStream fos = new FileOutputStream(url);
			workbook.write(fos);
			fos.close();
		}

		return -1;
	}
}
